package cn.exrick.xboot.modules.Information.controller;

import cn.exrick.xboot.common.utils.PageUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.Equipments.service.IEquipmentsService;
import cn.exrick.xboot.modules.Information.entity.RiverTourHistory;
import cn.exrick.xboot.modules.Information.entity.RiverUser;
import cn.exrick.xboot.modules.Information.entity.River;
import cn.exrick.xboot.modules.Information.entity.WorkCondition;
import cn.exrick.xboot.modules.Information.service.IRiverUserService;
import cn.exrick.xboot.modules.Information.service.IriverService;
import cn.exrick.xboot.modules.activiti.entity.business.EventReport;
import cn.exrick.xboot.modules.activiti.service.business.EventReportService;
import cn.exrick.xboot.modules.base.entity.Department;
import cn.exrick.xboot.modules.base.entity.User;
import cn.exrick.xboot.modules.base.service.DepartmentService;
import cn.exrick.xboot.modules.base.service.UserService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Lyg
 */
@Slf4j
@RestController
@Api(description = "河流信息管理接口")
@RequestMapping("/xboot/river")
@Transactional
public class RiverController {

    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private UserService userService;
    @Autowired
    private IriverService iriverService;
    @Autowired
    private IEquipmentsService iEquipmentsService;
    @Autowired
    private IRiverUserService iRiverUserService;
    @Autowired
    private EventReportService eventReportService;

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "通过id获取")
    public Result<River> get(@PathVariable Long id){

        River river = iriverService.getById(id);
        if(null != river){
            if(StrUtil.isNotBlank(river.getWithDepartment())){
                Department department = departmentService.get(river.getWithDepartment());
                river.setWithDepartmentName(department.getTitle());
            }
            //人员赋值
            QueryWrapper en = new QueryWrapper();
            en.eq("river_id",river.getId());
            river.setRiverUser(iRiverUserService.list(en));
            river.setEquipments(iEquipmentsService.list(en));
        }
        return new ResultUtil<River>().setData(river);
    }

    @RequestMapping(value = "/getAllByUserName", method = RequestMethod.GET)
    @ApiOperation(value = "根据用户名获取全部数据")
    public Result<List<River>> getAllByUserName(String userName){

        QueryWrapper queren = new QueryWrapper();

            User user=userService.findByUsername(userName);
            if(user != null){
                queren.like("users",user.getId());
            }else{
                queren.eq("users",userName);
            }
            List<River> list = iriverService.list(queren);
        return new ResultUtil<List<River>>().setData(list);
    }

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ApiOperation(value = "获取全部数据")
    public Result<List<River>> getAll(){


        List<River> list = iriverService.list();
        return new ResultUtil<List<River>>().setData(list);
    }

    @RequestMapping(value = "/getByPage", method = RequestMethod.GET)
    @ApiOperation(value = "分页获取")
    public Result<IPage<River>> getByPage(@ModelAttribute PageVo page,@RequestParam Map map){
        QueryWrapper queren = new QueryWrapper();
        if(map.containsKey("withDepartment")){
            queren.eq("with_department",map.get("withDepartment"));
        }
        if(map.containsKey("riverName")){
            queren.eq("river_name",map.get("riverName"));
        }
        if(map.containsKey("userName")){
            User user=userService.findByUsername(""+map.get("userName"));
            if(user != null){
                queren.like("users",user.getId());
            }else{
                queren.eq("users",map.get("userName"));
            }
        }
        IPage<River> data = iriverService.page(PageUtil.initMpPage(page),queren);
        for (River rivers :data.getRecords()) {
            //部门赋值
            if(StrUtil.isNotBlank(rivers.getWithDepartment())){
                Department department = departmentService.get(rivers.getWithDepartment());
                rivers.setWithDepartmentName(department.getTitle());
            }
            //人员赋值
            QueryWrapper en = new QueryWrapper();
            en.eq("river_id",rivers.getId());
            rivers.setRiverUser(iRiverUserService.list(en));
//            if(riverUser.size()>0){
//                List<String> ids = new ArrayList<>();
//                riverUser.forEach(item->{
//                    ids.add(item.getUserId());
//                });
//                rivers.setUserIds(userService.findByIdIn(ids));
//            }
        }
        return new ResultUtil<IPage<River>>().setData(data);
    }

    @RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST)
    @ApiOperation(value = "编辑或更新数据")
    public Result<River> saveOrUpdate(@ModelAttribute River river){

        if(iriverService.saveOrUpdate(river)){
            if(StringUtils.isNotEmpty(river.getRiverDetail())){
                //每次先删除
                QueryWrapper en = new QueryWrapper();
                en.eq("river_id",river.getId());
                iRiverUserService.remove(en);
                //插入
                Gson gson = new Gson();
                List<RiverUser> riverUser = gson.fromJson(river.getRiverDetail(), new TypeToken<List<RiverUser>>() {}.getType());
                //插入用户河流中间表
                if(riverUser.size()>0){
                    riverUser.forEach((item)->{
                        item.setRiverId(river.getId());
                        item.setCreateTime(new Date());
                        iRiverUserService.saveOrUpdate(item);
                    });
                }
            }
            return new ResultUtil<River>().setData(river);
        }
        return new ResultUtil<River>().setErrorMsg("操作失败");
    }

    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过id删除")
    public Result<Object> delAllByIds(@PathVariable Long[] ids){
        for(Long id : ids){
            iriverService.removeById(id);
            //删除中间表数据
            QueryWrapper en = new QueryWrapper();
            en.eq("river_id",id);
            iRiverUserService.remove(en);
        }
        return new ResultUtil<Object>().setSuccessMsg("批量通过id删除数据成功");
    }

    @RequestMapping(value = "/getRiverPeoples", method = RequestMethod.POST)
    @ApiOperation(value = "通过ids获取正在巡河的人")
    public Result<List<RiverTourHistory>> getRiverPeople(@RequestParam String ids, String time){
        Map<String, Object> param = new HashMap<>();
//        param.put("ids",ids);
        if(!"".equals(ids)){
            String[] idss = ids.split(",");
            param.put("ids",idss);
        }
        param.put("time",time);
        List<RiverTourHistory> riverTourHistories = iriverService.findRiverPeople(param);
        for(RiverTourHistory riverTourHistory:riverTourHistories){
            if(StrUtil.isNotBlank(riverTourHistory.getUserId())){
                if(userService.get(riverTourHistory.getUserId())!=null) {
                    User u = userService.get(riverTourHistory.getUserId());
                    if (StrUtil.isNotBlank(u.getDepartmentId())) {
                        Department department = departmentService.get(u.getDepartmentId());
                        u.setDepartmentTitle(department.getTitle());
                    }
                    riverTourHistory.setUser(u);
                }
            }
        }
        return new ResultUtil<List<RiverTourHistory>>().setData(riverTourHistories);
    }

    @RequestMapping(value = "/getRiverPeople", method = RequestMethod.POST)
    @ApiOperation(value = "获取正在巡河的人")
    public Result<List<RiverTourHistory>> getRiverPeople(@RequestParam String time){
        Map<String, Object> param = new HashMap<>();
        param.put("time",time);
        List<RiverTourHistory> riverTourHistories = iriverService.findRiverPeople(param);
        for(RiverTourHistory riverTourHistory:riverTourHistories){
            if(StrUtil.isNotBlank(riverTourHistory.getUserId())){
                if(userService.get(riverTourHistory.getUserId())!=null) {
                    User u = userService.get(riverTourHistory.getUserId());
                    if (StrUtil.isNotBlank(u.getDepartmentId())) {
                        Department department = departmentService.get(u.getDepartmentId());
                        u.setDepartmentTitle(department.getTitle());
                    }
                    param.put("userName",u.getUsername());
                    List<EventReport> eventReports = eventReportService.findRiverEventByUserName(param);
                    riverTourHistory.setUser(u);
                    riverTourHistory.setEventReport(eventReports);
                }
            }
        }
        return new ResultUtil<List<RiverTourHistory>>().setData(riverTourHistories);
    }

    @RequestMapping(value = "/getRiverByWithDepartmentid/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "按单位id查询河流")
    public Result<List<River>> getRiverByWithDepartmentid(@PathVariable Long id){
        QueryWrapper queren = new QueryWrapper();
        queren.eq("with_department",id);
        List<River> river = iriverService.list(queren);
        return new ResultUtil<List<River>>().setData(river);
    }

    @RequestMapping(value = "/getWorkConditionForm", method = RequestMethod.POST)
    @ApiOperation(value = "获取河长工作制情况统计数据")
    public Result<List<WorkCondition>> getWorkConditionForm(@RequestParam Map map){
        List<WorkCondition> workConditionList = iriverService.getWorkConditionForm(map);

        return new ResultUtil<List<WorkCondition>>().setData(workConditionList);
    }
}
